const urllib = require('urllib');
const TIMEOUT = 10000;
const Utils = require('../utils');

class HttpClient {

  http(url, options) {
    const method = options.method;
    const start = Date.now();
    return new Promise((r, j) => {
      urllib.request(url, options)
        .then(result => {
          Utils.Logger.info(`
          s_HttpClient_${method}_info:
          URL: ${url}
          请求参数: ${JSON.stringify(options.data)}
          结果: ${typeof result === 'object' ? JSON.stringify(result) : result}
          花费时间: ${(Date.now() - start) / 1000}s
          `);
          return r(result);
        })
        .catch(err => {
          Utils.Logger.error(err.stack);
          return j(err);
        });
    });
  }

  async get(_options) {
    const {
      url,
      data,
      timeout,
      options = null
    } = _options;
    const result = await this.http(url, {
      method: 'GET',
      data,
      dataType: 'json',
      timeout: timeout || TIMEOUT,
      ...options
    });

    if (
      result &&
      result.res &&
      result.res.statusCode === 200 &&
      result.res.data
    ) {
      return result.res.data;
    }
    return null;
  }

  async post(_options) {
    const {
      url,
      data,
      headers,
      timeout,
      dataType,
      options = null
    } = _options;
    const result = await this.http(url, {
      method: 'POST',
      data,
      dataType: dataType || 'json',
      headers,
      timeout: timeout || TIMEOUT,
      ...options
    });

    if (
      result &&
      result.res &&
      result.res.statusCode === 200 &&
      result.res.data
    ) {
      return result.data;
    }
    return null;
  }
}

module.exports = new HttpClient();